<script setup lang="ts">
import {useDownloadFile} from './useDownloadFile'

const props = defineProps<{
  url: string
  filename: string
  onSuccess?: () => void
}>()

const {
  progress,
  status,
  downloadedSize,
  totalSize,
  start,
  cancel,
  save
} = useDownloadFile()

const doDownload = () => {
  start(props.url, (a, b) => console.log(a, b), props.onSuccess)
}

//将字节转为合适的格式
function formatSize(bytes: number): string {
  if (!bytes) return '0B'
  const units = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(1024))
  return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + units[i]
}
</script>

<template>
  <div class="download-card">
    <div class="header">
      <span class="filename" :title="filename">{{ filename }}</span>
      <button v-if="status === 'idle'" class="cancel-btn" @click="doDownload">下载</button>
      <button v-if="status === 'downloading'" class="cancel-btn" @click="cancel">取消</button>
    </div>

    <div class="progress-bar">
      <div class="progress-bar-fill" :style="{ width: progress + '%' }"></div>
    </div>

    <div class="info">
      <template v-if="status === 'downloading'">
        {{ formatSize(downloadedSize) }} / {{ formatSize(totalSize) }} ({{ progress }}%)
      </template>
      <template v-else-if="status === 'ready'">
        ✅ 下载完成
        <button class="save-btn" @click="save(filename)">保存</button>
      </template>
      <span v-else-if="status === 'success'" class="success">🎉 已保存</span>
      <span v-else-if="status === 'error'" class="error">❌ 下载失败</span>
      <span v-else-if="status === 'canceled'" class="cancel">⛔ 已取消</span>
    </div>
  </div>
</template>

<style scoped>
.download-card {
  border: 1px solid #ddd;
  border-radius: 10px;
  padding: 16px;
  width: 350px;
  background-color: #fff;
  font-family: sans-serif;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.filename {
  font-weight: bold;
  max-width: 240px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.cancel-btn, .save-btn {
  border: none;
  background: none;
  color: #007bff;
  cursor: pointer;
  font-size: 14px;
}

.progress-bar {
  height: 10px;
  background: #f0f0f0;
  border-radius: 5px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress-bar-fill {
  height: 100%;
  background: #409eff;
  transition: width 0.3s ease;
}

.info {
  font-size: 12px;
  color: #666;
}

.success {
  color: green;
}

.error {
  color: red;
}

.cancel {
  color: #888;
}
</style>
